package com.example.arithmeticleetcode.leetcode.September;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @program: arithmetic-leetcode
 * @description:
 * @author: FangZhen
 * @create: 2020-09-21 13:06
 **/
public class Demo16 {

    public static void main(String[] args) {
        String text = "  this   is  a sentence ";
        System.out.println(reorderSpaces(text) + "---");
    }

    public static String reorderSpaces(String text) {
        String trim = text.trim();
        String[] split = trim.split("\\s+");
        int count = 0;
        for (int i = 0, len = text.length(); i < len; i++) {
            if (' ' == text.charAt(i)) {
                count ++;
            }
        }
        if (split.length == 1) {
            StringBuilder stringBuilder = new StringBuilder(trim);
            if (count > 0) {
                for (int i = 0; i < count; i++) {
                    stringBuilder.append(" ");
                }
            }
            return stringBuilder.toString();
        }
        StringBuilder stringBuilder = new StringBuilder();
        int a = count / (split.length - 1);
        int b = count % (split.length - 1);
        StringBuilder aSb = new StringBuilder();
        for (int i = 0; i < a; i++) {
            aSb.append(" ");
        }
        StringBuilder bSb = new StringBuilder();
        for (int i = 0; i < b; i++) {
            bSb.append(" ");
        }
        for (int i  = 0, len = split.length; i < len; i++) {
            if (i < len - 1) {
                stringBuilder.append(split[i]).append(aSb.toString());
                continue;
            }
            stringBuilder.append(split[i]).append(bSb.toString());
        }
        return stringBuilder.toString();
    }
}
